﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmartMathLibrary;

namespace SmartMathLibrary.LinearEquationSolvers.Preconditioners
{
    /// <summary>
    /// This class represents a matrix preconditioner, which calculates the precondition matrix by using the 
    /// Jacobi method.
    /// </summary>
    [Serializable]
    public class JacobiPreconditioner : IPreconditioner
    {
        /// <summary>
        /// The source matrix for the precondition process.
        /// </summary>
        private SquareMatrix sourceMatrix;

        /// <summary>
        /// Initializes a new instance of the <see cref="JacobiPreconditioner"/> class.
        /// </summary>
        /// <param name="sourceMatrix">The source matrix for the precondition process.</param>
        public JacobiPreconditioner(SquareMatrix sourceMatrix)
        {
            if (sourceMatrix == (SquareMatrix) null)
            {
                throw new ArgumentNullException("sourceMatrix");
            }

            this.sourceMatrix = sourceMatrix;
        }

        /// <summary>
        /// Gets or sets the source matrix for the precondition process.
        /// </summary>
        /// <value>The source matrix for the precondition process.</value>
        public SquareMatrix SourceMatrix
        {
            get { return sourceMatrix; }
            set { sourceMatrix = value; }
        }

        /// <summary>
        /// Computes the precondition matrix of the specified matrix.
        /// </summary>
        /// <returns>
        /// The computed precondition matrix of the original matrix.
        /// </returns>
        public Matrix ComputePreconditionMatrix()
        {
            Matrix result = new Matrix(this.sourceMatrix.Rows, this.sourceMatrix.Rows);

            for (int i = 0; i < this.sourceMatrix.Rows; i++)
            {
                result.SetValueAtPosition(i, i, 1 / this.sourceMatrix.GetValueAtPosition(i, i));
            }

            return result;
        }
    }
}